﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace SearchScreen.SDK
{
    public class CriteriaTemplateSelector : DataTemplateSelector
    {
        private Dictionary<Type, DataTemplate> dataTemplateCache = new Dictionary<Type, DataTemplate>();

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var type = item.GetType();

            DataTemplate template;

            if (!this.dataTemplateCache.TryGetValue(type, out template))
            {
                template = new DataTemplate(type);
                var factory = template.VisualTree = new FrameworkElementFactory(typeof(StackPanel));
                factory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

                foreach (var p in type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public))
                {
                    var customAttributes = p.GetCustomAttributes(true);

                    var consideredAttribute = customAttributes.OfType<SearchCriteriaAttribute>().FirstOrDefault();

                    if (null != consideredAttribute)
                    {
                        var labelFactory = new FrameworkElementFactory(typeof(TextBlock));
                        labelFactory.SetValue(TextBlock.TextProperty, consideredAttribute.Label);

                        var elementFactory = FrameworkElementFactoryFactory.Instance.GetFactory(consideredAttribute, p);

                        factory.AppendChild(labelFactory);
                        factory.AppendChild(elementFactory);
                    }
                }
            }
            return template;
        }
    }
}
